package com.foreknow.elm.dao.impl;

import com.foreknow.elm.dao.OrderdetailetDao;
import com.foreknow.elm.po.Food;
import com.foreknow.elm.po.Orderdetailet;
import com.foreknow.elm.po.Orders;
import com.foreknow.elm.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class OrderdetailetDaoImpl implements OrderdetailetDao {
    private Connection con;
    private PreparedStatement pst;
    private ResultSet rs;
    private int result = 0;
    @Override
    public int save(List<Orderdetailet> list) throws SQLException{
        String sql = "insert into orderdetailet(orderId,foodId,quantity) values ";
        StringBuffer s = new StringBuffer();
        s.append(sql);
        for (int i = 0;i<list.size();i++){
            Orderdetailet orderdetailet = list.get(i);
            s.append("("+orderdetailet.getOrderId()+","+orderdetailet.getFoodId()+","+orderdetailet.getQuantity()+")"+",");
        }
        String s1 = s.substring(0, s.length() - 1);//去掉最后一个,
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(s1);
            result= pst.executeUpdate();
        } finally {
            DBUtil.close(pst);
        }
        return result;
    }

    @Override
    public List<Orderdetailet> save2(Orders orders) throws SQLException{
        String sql = "SELECT * from orderdetailet,food where orderdetailet.foodId=food.foodId and orderdetailet.orderId=?";
        List<Orderdetailet> list = new ArrayList<>();
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql);
            pst.setInt(1,orders.getOrderId());
            rs = pst.executeQuery();
            while(rs.next()){
                Food food = new Food();
                Orderdetailet orderdetailet = new Orderdetailet();

                orderdetailet.setOdId(rs.getInt("odId"));
                orderdetailet.setOrderId(rs.getInt("orderId"));
                orderdetailet.setFoodId(rs.getInt("foodId"));
                orderdetailet.setQuantity(rs.getInt("quantity"));

                food.setFoodId(rs.getInt("foodId"));
                food.setFoodName(rs.getString("foodName"));
                food.setFoodExplain(rs.getString("foodExplain"));
                food.setFoodImg(rs.getString("foodImg"));
                food.setFoodPrice(rs.getDouble("foodPrice"));
                food.setBusinessId(rs.getInt("businessId"));
                food.setRemarks(rs.getString("remarks"));

                orderdetailet.setFood(food);
                list.add(orderdetailet);
            }
        } finally {
            DBUtil.close(pst);
        }
        return list;
    }


}
